package com.zjyd.douyangauth.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjyd.douyangcommoncore.entity.DyUsers;
import com.zjyd.douyangcommoncore.result.Result;
import com.zjyd.douyangcommoncore.service.DyUsersService;
import com.zjyd.douyangcommoncore.vo.DyUsersRegisterByPasswordVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录
 */
@Slf4j
@RestController
@Tag(name = "登录")
@RequestMapping("/douyang/auth/login")
public class LoginController {

    @Autowired
    private DyUsersService dyUsersService;

    /**
     * 用户名密码登录
     */
    @Operation(summary = "用户名密码登录")
    @PostMapping("/usernamePassword")
    public Result usernamePassword(@Valid @RequestBody DyUsersRegisterByPasswordVO dyUsersRegisterByPasswordVO){
        log.info("123");
        //通过用户名查询用户
        QueryWrapper<DyUsers> queryWrapper = new QueryWrapper<DyUsers>()
                .eq("username", dyUsersRegisterByPasswordVO.getUsername());
        DyUsers one = dyUsersService.getOne(queryWrapper);
        if (one == null){
            return Result.error("用户名或密码错误");
        }
        //获取这个用户的盐值
        String salt = one.getSalt();
        //Md5加密
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        log.info("密码为：{}",dyUsersRegisterByPasswordVO.getPassword());
        log.info("盐值为：{}",salt);
        String passwordSalt = md5.digestHex(dyUsersRegisterByPasswordVO.getPassword() + salt);
        log.info("加密后的密码为：{}",passwordSalt);
        //和数据库的密码比较
        if (!passwordSalt.equals(one.getPassword())){
            return Result.error("用户名或密码错误");
        }
        //通过id得到token
        StpUtil.login(one.getId());
        String token = StpUtil.getTokenInfo().getTokenValue();
        return Result.success(token).message("登录成功");
    }
}
